package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
    @Autowired
    private CategoryService categoryService;


    /**
     * 新增分类
     *
     */
    @PostMapping
    public R save(@RequestBody Category category) {
        log.info("category:{}", category);
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     *
     */
    @GetMapping("/page")
    public R page(int page, int pageSize) {
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //orderBy根据sort字段升序排序Asc
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    @GetMapping("/{id}")       //根据id查
    public R getById(@PathVariable Long id) {
        Category byId = categoryService.getById(id);
        return R.success(byId);
    }

    /**
     * 根据id删除分类
     */
    @DeleteMapping
    public R deleteById(Long id) {
        categoryService.deleteById(id);
        return R.success("删除成功！");
    }

    @PutMapping     //修改
    public R updateById(@RequestBody Category category) {
        //已设置公共字段自动信息补全
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R list(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //添加条件
        lqw.eq(category.getType() != null,Category::getType,category.getType());
        //添加排序条件
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
